<script setup>
import LteModal from "../../../layout/components/LteModal.vue";
import LteAlert from "../../../layout/components/LteAlert.vue";
import LteTree from "../../../layout/components/LteTree.vue";
import clientPermissions from "./configs/clientPermissions";
import { reactive, getCurrentInstance, nextTick } from 'vue';
import { AllPermissions } from "../../../apis/system/base";

const instance = getCurrentInstance();

const data = reactive({
    show: false,
    callback: null,
    model: {},
    errors: {},
    permissions: [],
});

const load = function(callback) {
    data.loading = true;
    AllPermissions({}).then((res) => {
        let servicePermissions = res.data.result;
        data.permissions = merge(servicePermissions, clientPermissions);
        if(callback!=null && typeof callback === 'function'){
            callback();
        }
    }).finally((res) => {
        data.loading = false;
    });
};

const merge = function(src1, src2) {
    let tmp = {};
    if(src1){
        for (let i = 0; i < src1.length; i++) {
            let item = src1[i];
            if(tmp[item.label] !== undefined && tmp[item.label] != null){
                let children = merge(tmp[item.label]?.children, item?.children);
                tmp[item.label] = {label: item?.label, value: item?.value, children: children};
            } else {
                let children = merge(item?.children, null);
                tmp[item.label] = {label: item?.label, value: item?.value, children: children};
            }
        }
    }
    if(src2){
        for (let i = 0; i < src2.length; i++) {
            let item = src2[i];
            if(tmp[item.label] !== undefined && tmp[item.label] != null){
                let children = merge(tmp[item.label]?.children, item?.children)
                tmp[item.label] = {label: item?.label, value: item?.value, children: children};
            } else {
                let children = merge(item?.children, null);
                tmp[item.label] = {label: item?.label, value: item?.value, children: children};
            }
        }
    }

    let res = [];
    for (const key in tmp) {
        res.push(tmp[key]);
    }

    return res;
};

const check = function(model, permissions){
    instance.refs.refAlert.close();
    if(model.is_system) {
        let items = [
            "system_users", "system_users_create", "system_users_update", "system_users_delete", "system_users_roles",
            "system_roles", "system_roles_create", "system_roles_update", "system_roles_delete", "system_roles_permissions",
        ];
        for(let i=0; i<items.length; i++){
            let item = items[i];
            if(!permissions.includes(item)){
                instance.refs.refAlert.open('danger', '系统角色必须拥有所有系统管理权限');
                return false;
            }
        }
    }
    return true;
};

const submit = function(e){
    //获取取值
    let permissions = instance.refs.refTree.getCheckedValues();
    //执行判断
    if(!check(data.model, permissions)) {
        return;
    }
    //返回设值
    data.model.permissions = permissions;
    //执行回调
    if(data.callback){
        data.callback(data.model);
    }
};

defineExpose({
    open : function(model, callback){
        //设置属性
        data.model = JSON.parse(JSON.stringify(model));
        data.errors = [];
        data.show = true;
        data.callback = callback;
        //设置组件
        instance.refs.refAlert.close();
        //加载权限
        load(async () => {
            //等待渲染
            await nextTick();
            //设置初始展开层级
            instance.refs.refTree.expandLevel(1);
            //设置取值
            instance.refs.refTree.setCheckedValues(data.model?.permissions || []);
        });
    },
    close : function(){
        //设置属性
        data.show = false;
    },
    error : function(message){
        //显示弹窗
        instance.refs.refAlert.open('danger', message);
    },
});
</script>

<template>
    <lte-modal v-model="data.show" title="权限">
        <div>
            <div class="row">
                <div class="col-sm">
                    <lte-alert ref="refAlert"></lte-alert>
                </div>
            </div>
            <div class="row">
                <div class="col-sm">
                    <lte-tree class="tree" ref="refTree" :nodes="data.permissions"></lte-tree>
                </div>
            </div>
            <div class="row">
                <div class="col-sm">
                    <div class="actions">
                        <button type="button" class="btn btn-xs btn-primary" @click="instance.refs.refTree.checkedAll()"><i class="fa fa-check"></i> 全选</button>
                        <button type="button" class="btn btn-xs btn-default" @click="instance.refs.refTree.checkedClear()"><i class="fa fa-reply"></i> 清空</button>
                    </div>
                </div>
            </div>
        </div>
        <template #footer>
            <button class="btn btn-default" @click="data.show = false">取消</button>
            <button class="btn btn-primary float-right" @click="submit">确认</button>
        </template>
    </lte-modal>
</template>

<style scoped>
.actions{
    margin-top: 10px;
}
.actions button{
    margin-right: 6px;
}
.actions button:last-child{
    margin-right: 0;
}
</style>